<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box {
            position: relative;
            width: 500px;
            height: 500px;
            margin: 20px auto;
            background-color: black;
        }

        .box .tank {
            position: absolute;
            left: calc(50% - 30px);
            top: calc(100% - 60px);
            width: 60px;
            height: 60px;
            text-align: center;
            line-height: 60px;
            background: url('./images/tankT.png') center no-repeat;
        }

        .box img {
            position: absolute;
            left: calc(50% - 10px);
            top: calc(100% - 40px);
            width: 20px;
            height: 20px;
        }

        /* 敌机 */
        .box .prop {
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            right: 0;
            width: 30px;
            height: 30px;
            margin: auto;
            border-radius: 50%;
            text-align: center;
            line-height: 30px;
            background-color: #fff;
        }

        .box .ball {
            position: absolute;
            border-radius: 50%;
            box-shadow: 0 0 10px #888888 inset;
        }

        .btn {
            display: block;
            width: 80px;
            height: 30px;
            margin: 20px auto;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="tank"></div>
        <div class="prop">敌</div>
    </div>
    <button class="btn">增加敌机</button>

<script>
    // 获取元素
    const box = document.querySelector('.box');
    const tank = document.querySelector('.tank');
    const btn = document.querySelector('.btn');

    // 创建敌机
    btn.onclick = function () {
        let ball = document.createElement('div'),
            size = 20 + Math.floor(Math.random() * 5) * 10,
            color = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple'][Math.floor(Math.random() * 7)],
            stepX = (5 + Math.floor(Math.random() * 10)) * ([-1, 1].sort((a, b) => Math.random() - 0.5).shift()),
            stepY = (5 + Math.floor(Math.random() * 10)) * ([-1, 1].sort((a, b) => Math.random() - 0.5).shift()),
            top = box.clientWidth / 2 - size / 2,
            left = box.clientHeight / 2 - size / 2;
        box.appendChild(ball);
        ball.className = 'ball';

        let timer = setInterval(function () {
            ball.style.cssText = `width:${size}px;height:${size}px;background:${color};top:${top}px;left:${left}px`;
            // 打坦克
            beatTank();
            top += stepY
            if (top < 0 || top > box.clientHeight - size) stepY = -stepY;
            left += stepX;
            if (left < 0 || left > box.clientWidth - size) stepX = -stepX;
        }, 500)
    }

    // 攻打坦克
    function beatTank() {
        const balls = box.querySelectorAll('.ball');
        if (balls) {
            balls.forEach(function (el, i) {
                if (el.offsetTop + el.offsetHeight - tank.offsetTop > 0 && el.offsetTop + el.offsetHeight - tank.offsetTop < tank.offsetHeight && el.offsetLeft + el.offsetWidth - tank.offsetLeft > 0 && el.offsetLeft + el.offsetWidth - tank.offsetLeft < tank.offsetWidth) {
                    tank.remove();
                }
            })
        }
    }

    // 键盘事件
    let count = 1; //计数器
    let direction = 'T'; //坦克方向
    document.addEventListener('keydown', function (e) {
        // 最大活动范围值
        let diffX = box.clientWidth - tank.offsetWidth;
        let diffY = box.clientHeight - tank.offsetHeight;
        // 步进值
        let stepX = parseInt(diffX / 50);
        let stepY = parseInt(diffY / 50);
        // 坦克边距
        let top = tank.offsetTop;
        let left = tank.offsetLeft;

        // 按键码 左37 上38 右39 下40

        // 左移动
        if (e.keyCode == 37) {
            direction = 'L';
            left -= stepX;
            if (left < 0) left = 0;
            tank.style.left = `${left}px`;
            tank.style.backgroundImage = count % 2 ? 'url(./images/tankL.png' : 'url(./images/tankL1.png)';
            count++;
        }
        // 上移动
        if (e.keyCode == 38) {
            direction = 'T';
            top -= stepY;
            if (top < 0) top = 0;
            tank.style.top = `${top}px`;
            tank.style.backgroundImage = count % 2 ? 'url(./images/tankT.png)' : 'url(./images/tankT1.png)';
            count++;
        }
        // 右移动
        if (e.keyCode == 39) {
            direction = 'R';
            left += stepX;
            if (left > diffX) left = diffX;
            tank.style.left = `${left}px`;
            tank.style.backgroundImage = count % 2 ? 'url(./images/tankR.png)' : 'url(./images/tankR1.png)';
            count++;
        }
        // 下移动
        if (e.keyCode == 40) {
            direction = 'B';
            top += stepY;
            if (top > diffY) top = diffY;
            tank.style.top = `${top}px`;
            tank.style.backgroundImage = count % 2 ? 'url(./images/tankB.png' : 'url(./images/tankB1.png)';
            count++;
        }

        // 空格发弹
        if (e.keyCode == 32) {
            shot(direction);
        }

        // 装弹
        function shot(direction) {
            let pStepX = 10;
            let pStepY = 10;
            let pTop = top + 20;
            let pLeft = left + 20;
            box.appendChild(document.createElement('img')).src = `./images/zidan${direction}.png`;
            box.querySelectorAll('img').forEach(function (el, i) {
                el.style.top = `${pTop}px`;
                el.style.left = `${pLeft}px`;
            });
            let timer = setInterval(function () {
                if ((direction == 'T' && pTop <= 0) || (direction == 'L' && pLeft <= 0) || (direction == 'B' && pTop > box.offsetHeight - 20) || (direction == 'R' && pLeft > box.offsetWidth - 20)) {
                    clearInterval(timer);
                    box.querySelector('img').remove();
                }
                if (direction == 'T' || direction == 'B') {
                    if (direction == 'T') pTop -= pStepY;
                    else pTop += pStepY;
                    box.querySelector('img') && (box.querySelector('img').style.top = `${pTop}px`);
                    // 攻打敌机
                    beatBall(pLeft, pTop);
                }
                if (direction == 'L' || direction == 'R') {
                    if (direction == 'L') pLeft -= pStepX;
                    else pLeft += pStepX;
                    box.querySelector('img') && (box.querySelector('img').style.left = `${pLeft}px`);
                    // 攻打敌机
                    beatBall(pLeft, pTop);
                }
            }, 15);
        }

        // 攻打敌机
        function beatBall(posX, posY) {
            const balls = box.querySelectorAll('.ball');
            if (balls) {
                balls.forEach(function (el, i) {
                    if (posY + 20 - el.offsetTop > 0 && posY + 20 - el.offsetTop < el.offsetHeight && posX + 20 - el.offsetLeft > 0 && posX + 20 - el.offsetLeft < el.offsetWidth) {
                        el.remove();
                    }
                })
            }
        }
    });
</script>
</body>

</html>